class Solution {
public:
    string ReverseSentence(string str) {
        string res=str;
        int n=str.size();
        if(str.empty())
            return res;
        Reverse(res,0,n-1);
        int left=0,right=0;
        while(right<n){
            if(res[right]==' '){
                Reverse(res,left,right-1);
                left=right+1;
                right++;
            }else if(right==n-1){
                Reverse(res,left,right);
                right++;
            }else
                right++;
        }
        return res;
    }
    void Reverse(string& str,int left, int right){
        while(left<right){
            swap(str[left],str[right]);
            left++;
            right--;
        }
    }
};